package com.springmvc.utils.majiang;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.springmvc.cache.CacheKey;
import com.springmvc.cache.MapCacheManager;
import com.springmvc.utils.SpringUtils;
import com.springmvc.web.majiang.entity.Room;
import com.springmvc.web.majiang.entity.User;
import com.springmvc.web.majiang.service.IRoomService;
import com.springmvc.web.majiang.service.IUserService;

public class RoomUtil {

	@Autowired
	static IUserService	userService	= (IUserService) SpringUtils.getBean(IUserService.class);

	@Autowired
	static IRoomService	roomService	= (IRoomService) SpringUtils.getBean(IRoomService.class);

	public static void setRoomUser(Long userid, Long roomid, Integer position) {
		//		Long roomid = room.getId();
		//		Long userid = user.getId();
		//		Integer position = user.getPosition();

		User user = userService.selectById(userid);
		Room room = roomService.selectById(roomid);

		room = roomService.selectById(roomid);
		MapCacheManager cache = MapCacheManager.getInstance();
		cache.put(CacheKey.setRoomNameKey(roomid), room.getRoomname());//房间名称
		cache.put(CacheKey.setRoomUseridKey(roomid), room.getRoomuserid());//增加房主
		cache.put(CacheKey.setRoomPositionUseridKey(roomid, position), userid);//增加用户
		cache.put(CacheKey.setRoomTypeKey(roomid), 1);//增加用户
		cache.put(CacheKey.setUserNameKey(userid), user.getUsername());//增加用户
	}

	public static void removeRoomUser(Long roomid, Integer position) {

		MapCacheManager cache = MapCacheManager.getInstance();
		String roomuserid = (String) cache.get(CacheKey.setRoomUseridKey(roomid));//增加房主
		String userid = (String) cache.get(CacheKey.setRoomPositionUseridKey(roomid, position));
		if (StringUtils.equals(userid, roomuserid)) {
			cache.del(CacheKey.setRoomNameKey(roomid));//房间名称
			cache.del(CacheKey.setRoomUseridKey(roomid));//增加房主
			cache.del(CacheKey.setRoomPositionUseridKey(roomid, 1));
			cache.del(CacheKey.setRoomPositionUseridKey(roomid, 2));
			cache.del(CacheKey.setRoomPositionUseridKey(roomid, 3));
			cache.del(CacheKey.setRoomPositionUseridKey(roomid, 4));
			cache.del(CacheKey.setRoomTypeKey(roomid));
		} else {
			cache.del(CacheKey.setRoomPositionUseridKey(roomid, 2));
			cache.set(CacheKey.setRoomTypeKey(roomid), 2);
		}
		cache.del(CacheKey.setUserNameKey(Long.valueOf(userid)));

	}
}
